#!/bin/bash

PROJECT_NAME=northwind

CONTEXT_ROOT=$PROJECT_NAME
WAR_FILE=$PROJECT_NAME'.war'
APP_NAME=$PROJECT_NAME'_war'
DOWNLOAD_PATH='http://192.168.83.145:8080/jenkins/job/'$PROJECT_NAME'/ws/web/target/'$WAR_FILE

RETVAL=0
TMP_DIR=/var/tmp

WSIP=192.168.84.92
WSPORT=8880
WSUSER=wsadmin
WSPASSWORD=password
WSPATH=/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/bin
WSADMIN=$WSPATH'/wsadmin.sh'
WSSYNC=$WSPATH'/syncNode.sh'
HOST_NAME=default_host
SERVER_NAME=webserver1
CELL_NAME=Dmgr01NodeCell
NODE_NAME=Default01Node
CLUSTER_NAME=testclu
CLUSTER_MEMBER=app1

deploy() {

	rm -f $WAR_FILE
	wget $DOWNLOAD_PATH
	
	CMD='$AdminApp install "'$WAR_FILE'" {-contextroot "'$CONTEXT_ROOT'" -usedefaultbindings -defaultbinding.virtual.host '$HOST_NAME' -cell '$CELL_NAME' -node '$NODE_NAME' -server '$SERVER_NAME' -cluster '$CLUSTER_NAME' -appname "'$APP_NAME'"}'
	echo $CMD > $TMP_DIR'/'$APP_NAME'_deploy.jacl'
	CMD='$AdminConfig save'
	echo $CMD >> $TMP_DIR'/'$APP_NAME'_deploy.jacl'
	
	$WSADMIN -lang jacl -f $TMP_DIR'/'$APP_NAME'_deploy.jacl'
	
	rm -f $TMP_DIR'/'$APP_NAME'_deploy.jacl'
	rm -f $WAR_FILE
	
	$WSSYNC $WSIP $WSPORT -user $WSUSER -password $WSPASSWORD
}

undeploy() {

	CMD='$AdminApp uninstall '$APP_NAME
	echo $CMD > $TMP_DIR'/'$APP_NAME'_undeploy.jacl'
	CMD='$AdminConfig save'
	echo $CMD >> $TMP_DIR'/'$APP_NAME'_undeploy.jacl'
	
	$WSADMIN -lang jacl -f $TMP_DIR'/'$APP_NAME'_undeploy.jacl'
	
	rm -f $TMP_DIR'/'$APP_NAME'_undeploy.jacl'
}

start() {

	CMD='set appManager [$AdminControl queryNames type=ApplicationManager,process='$CLUSTER_MEMBER',*]'
	echo $CMD > $TMP_DIR'/'$APP_NAME'_start.jacl'
	CMD='$AdminControl invoke $appManager startApplication '$APP_NAME
	echo $CMD >> $TMP_DIR'/'$APP_NAME'_start.jacl'
	
	$WSADMIN -lang jacl -f $TMP_DIR'/'$APP_NAME'_start.jacl'
	
	rm -f $TMP_DIR'/'$APP_NAME'_start.jacl'
}

stop() {

	CMD='set appManager [$AdminControl queryNames type=ApplicationManager,process='$CLUSTER_MEMBER',*]'
	echo $CMD > $TMP_DIR'/'$APP_NAME'_stop.jacl'
	CMD='$AdminControl invoke $appManager stopApplication '$APP_NAME
	echo $CMD >> $TMP_DIR'/'$APP_NAME'_stop.jacl'
	
	$WSADMIN -lang jacl -f $TMP_DIR'/'$APP_NAME'_stop.jacl'
	
	rm -f $TMP_DIR'/'$APP_NAME'_stop.jacl'
}

case "$1" in
	deploy)
		deploy
		;;
	undeploy)
		undeploy
		;;
	redeploy)
		undeploy
		deploy
		;;
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		stop
		start
		;;
	*)
		echo $"Usage: $0 {start|stop|restart|deploy|undeploy|redeploy}"
		RETVAL=1
esac
exit $RETVAL
